package net.mihome.app.ui.view;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.adapter.ListViewBigpaperAdapter;
import net.mihome.app.bean.Tweet;
import net.mihome.app.bean.TweetList;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.UIHelper;
import net.mihome.app.ui.LoginActivity;
import net.mihome.app.ui.TweetDetail;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.maxwin.view.XListView;

public class MihomeBigPaperView extends XListView {
//	private Handler handler;
    public ListViewBigpaperAdapter adapter;
	public List<Tweet> listData = new ArrayList<Tweet>();
	private AppContext appContext;
    private User curUser=null;
	private int numDefault=10;
	public int bigPaperType=TweetList.CATALOG_LASTEST;
	private MyViewLinster myViewLinster;
    private ImageLoader imageLoader;
    private Context context;

    protected static final String STATE_PAUSE_ON_SCROLL = "STATE_PAUSE_ON_SCROLL";
    protected static final String STATE_PAUSE_ON_FLING = "STATE_PAUSE_ON_FLING";
    protected boolean pauseOnScroll = false;
    protected boolean pauseOnFling = true;
	public MihomeBigPaperView(Context context, AttributeSet attrs) {
		super(context, attrs);
        this.context=context;
		afterInit();
		// TODO Auto-generated constructor stub
	}
	public MihomeBigPaperView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		afterInit();
		// TODO Auto-generated constructor stub
	}
	private void afterInit(){
        imageLoader=ImageLoader.getInstance();
        setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
		adapter = new ListViewBigpaperAdapter(getContext(),this, listData,R.layout.tweet_listitem,imageLoader);
        curUser=AppContext.getInstance().getLoginInfo();
		setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long arg3) {
				Tweet tweet = null;
				// 判断是否是TextView
				if (view!=null&&(view instanceof TextView)) {
					tweet = (Tweet) view.getTag();
				} else {
					TextView tv = (TextView) view.findViewById(R.id.tweet_listitem_username);
                    if(tv==null||tv.getTag()==null){
                        return ;
                    }
					tweet = (Tweet) tv.getTag();
				}
				if (tweet == null)
					return;   			
				// 跳转到动弹详情&评论页面
                Intent intent = new Intent(context, TweetDetail.class);
                intent.putExtra("tweet_id", tweet.getId());
                if(context instanceof Activity){
                    Activity mainActivity= (Activity) context;
                    mainActivity.startActivityForResult(intent,arg2);
                }else{
                    context.startActivity(intent);
                }
			}
		});
        setOnItemLongClickListener(itemLongClickListener);
		setPullLoadEnable(true);
		setPullRefreshEnable(true);
		setAdapter(adapter);
		appContext=(AppContext) getContext().getApplicationContext();
		setXListViewListener(new IXListViewListener() {
            /**
             * 继续加载最新的更多。
             * */
			@Override
			public void onRefresh() {
                prePage();
			}

            /**
             * 加载老的更多
             * */
			@Override
			public void onLoadMore() {
				nextPage();
			}
		});
	}
    public void initData(Integer bigPaperType){
        if(myViewLinster!=null){
            myViewLinster.onBeforeLoad();
        }
        if(bigPaperType!=null){
            this.bigPaperType=bigPaperType;
        }
        init();
    }

    public MyViewLinster getMyViewLinster() {
        return myViewLinster;
    }

    public void setMyViewLinster(MyViewLinster myViewLinster) {
        this.myViewLinster = myViewLinster;
    }

    /**
     * 长按大字报，弹出按钮
     * */
    private AdapterView.OnItemLongClickListener itemLongClickListener= new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int postion, long l) {
            if(listData!=null&&curUser!=null&&curUser.getName()!=null){
                final Tweet tweet= (Tweet) adapterView.getItemAtPosition(postion);
                if(curUser!=null&&curUser.getUid()==tweet.getAuthorId()){
                    UIHelper.showAlertDialog(getContext(),"删除大字报","确定删除吗",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    },new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            AppContext.getInstance().deleteBigPaper(tweet.getId(), new MiAsyncHttpResponseHandler() {
                                @Override
                                public void onSuccess(int arg0, Header[] arg1, ResponsePojo responsePojo) {
                                    listData.remove(postion-1);
                                    adapter.notifyDataSetChanged();
                                    Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                                    String msg = arg3.getMessage();
                                    if (msg == null || "".equals(msg.trim())) {
                                        msg = "删除失败~稍后再试吧";
                                    }
                                    Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();

                                }
                            });
                        }
                    });
                    return true;
                }else{
                    UIHelper.showAlertDialog(getContext(),"抱歉","无法操作他人大字报");
                }
            }else{
                UIHelper.showAlertDialog(getContext(),"抱歉","无法进行操作");
            }
            return true;
        }
    };
    /**
     * 下一页
     * */
    public void nextPage(){
        Long beginId=null;
        if(adapter.getCount()>0){
            beginId=adapter.getItemId(adapter.getCount()-1);
        }
        refreshData(AddType.ADD_TO_LAST,beginId,-numDefault);
    }
    /**
     * 上一页
     * */
    public void prePage(){
        Long beginId=null;
        if(adapter.getCount()>0){
//            beginId=adapter.getItemId(0);
            beginId=Long.valueOf(adapter.getMaxId());
        }
        refreshData(AddType.ADD_TO_FIRST,beginId,numDefault);
    }
    /**
     * 刷新当前页
     * */
    public void currentPage(Integer postion){
        Long beginId=null;
        int num=numDefault;
        if(adapter.getCount()>0&&postion!=null){
            //刷新某一条
            refreshBigpaper(postion);
        }else if(adapter.getCount()==0){
            //否则重新加载新数据
            refreshData(AddType.REPLACE,beginId,num);
        }
    }

    /**
     * 第一页
     * */
    public void init(){
        refreshData(AddType.INIT,null,numDefault);
    }
    /**
     * 跳到指定id
     * */
    public void redirtoUnread(Long pointId){
        refreshData(AddType.UNREAD,pointId,-numDefault);
    }
    /**
     * 刷新页面数据
     * */
    public void refreshData(final AddType addType,final Long pointId,int num){
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("num",num);
        requestParams.put("point_id",pointId);
        if(this.bigPaperType>0){
            requestParams.put("to_uid",this.bigPaperType);
        }
        requestParams.put("top_ids",adapter.getTopIds());
        AppContext.ASYNC_HTTP_CLIENT.get(context, URLs.MIHOME_GET_BIGPAPER_LIST2, requestParams, new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo responsePojo) {
                TweetList list = TweetList.parse(responsePojo);
                if (list != null && !list.getTweetlist().isEmpty() && getVisibility() == View.VISIBLE) {
                    if (addType == AddType.ADD_TO_FIRST) {
                        listData.addAll(0, list.getTweetlist());
                    } else if (addType == AddType.ADD_TO_LAST) {
                        listData.addAll(list.getTweetlist());
                    } else {
                        listData.clear();
                        listData.addAll(list.getTweetlist());
                    }
                }
                adapter.notifyDataSetChanged();
                stopRefresh();
                stopLoadMore();
                setRefreshTime("不久前");
                Long lastBigpaperId = AppContext.getInstance().getLastBigpaper();
                if ((pointId != null && adapter.getCount() > 0)||(lastBigpaperId==null)) {
                    /**
                     *如果pointId不为空，说明不是初次加载数据，这时如果第一条记录的id大于保存的用户阅读记录，则将第一条数据的id存入缓存中
                     */
//                    Long maxBigpaperId = adapter.getItemId(getFirstVisiblePosition());
                    Long maxBigpaperId = Long.valueOf(adapter.getMaxId());
                    if (lastBigpaperId==null||maxBigpaperId > lastBigpaperId) {
                        AppContext.getInstance().setLastBigpaper(maxBigpaperId);
                    }
                }
                if (myViewLinster != null) {
                    myViewLinster.onLoadComplete();
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                if(arg0==-104){
                    Toast.makeText(context,"您的账号被锁定，请联系管理员。",Toast.LENGTH_LONG).show();
                    //如果是被锁定，则清楚用户登录信息，跳转到登录界面
                    AppContext.getInstance().cleanCookie();
                    AppContext.getInstance().cleanLoginInfo();
                    AppContext.getInstance().clearAppCache();
                    Intent intent = new Intent(context, LoginActivity.class);
                    ((Activity)context).startActivity(intent);
                    try{
                        ((Activity)context).finish();
                    }catch (Exception e){
                    }
                }else if (myViewLinster != null) {
                    myViewLinster.onLoadComplete();
                }
                stopRefresh();
                stopLoadMore();
                setRefreshTime("不久前");
            }
        });
    }
    /**
     * 刷新指定postion、bigpaperid的数据
     * */
    public void refreshBigpaper(final int postion){
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        Long bigpaperId=getAdapter().getItemId(postion);
        requestParams.put("bigpaper_id",bigpaperId);
        AppContext.ASYNC_HTTP_CLIENT.get(context, URLs.MIHOME_GET_BIGPAPER_GET_BIGPAPER,requestParams,new MiAsyncHttpResponseHandler<Map>(){
            @Override
            public void onSuccess(int arg0, Header[] arg1,ResponsePojo<Map> responsePojo) {
                Tweet tweet=Tweet.parse(responsePojo.getData());
                if(tweet!=null){
                    listData.set(postion-1,tweet);
                    adapter.notifyDataSetChanged();
                }
                if(myViewLinster!=null){
                    myViewLinster.onLoadComplete();
                }
            }
            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                if(arg0==-104){
                    //如果是被锁定，则清楚用户登录信息，跳转到登录界面
                    AppContext.getInstance().cleanCookie();
                    AppContext.getInstance().cleanLoginInfo();
                    AppContext.getInstance().clearAppCache();
                    Intent intent = new Intent(context, LoginActivity.class);
                    context.startActivity(intent);
                    try{
                        ((Activity)context).finish();
                    }catch (Exception e){
                    }
                }else if(myViewLinster!=null){
                    myViewLinster.onLoadComplete();
                }
            }
        });
    }
    /**
     * 这几种类型个
     * */
    public enum AddType{
        INIT,ADD_TO_LAST,ADD_TO_FIRST,REPLACE,UNREAD
    }

    public List<Tweet> getListData() {
        return listData;
    }

    public void setListData(List<Tweet> listData) {
        this.listData.clear();
        this.listData.addAll(listData);
    }

}
